//
//  CMSChartsContentView.m
//  CMSCharts
//
//  Created by symbio on 2023/2/15.
//

#import "CMSChartsContentView.h"
#import <Masonry/Masonry.h>
#import "CMSCharts-Swift.h"
#import <YYKit/YYLabel.h>
#import <YYKit/NSAttributedString+YYText.h>
#import <CMSUIKit/CMSUIKit.h>
#import <CMSUIKit/UIControl+CMSBlocks.h>
#import <CMSFoundation/CMSFoundation.h>

@interface CMSChartsContentView ()<ChartViewDelegate>
@property (nonatomic, strong) YYLabel *headerLabel;
@end

@implementation CMSChartsContentView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    [self setupUIHeaderView];
    [self setupUIChartsView];
}

- (UIControl *)createControlWithTitle:(NSString *)title size:(CGSize)size {
    UIControl *control = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    control.clipsToBounds = YES;
    control.layer.borderColor = UIColor.redColor.CGColor;
    control.layer.borderWidth = 0.5;
    
    UIImageView *imageView = [[UIImageView alloc] init];
    [control addSubview:imageView];
    imageView.frame = CGRectMake(size.width - size.height, 0, size.height, size.height);
    imageView.backgroundColor = UIColor.lightTextColor;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, size.width - size.height, size.height)];
    [control addSubview:label];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = title;
    label.backgroundColor = UIColor.orangeColor;
    label.font = [UIFont systemFontOfSize:10];
    label.adjustsFontSizeToFitWidth = YES;
    label.textColor = UIColor.redColor;
    return control;
}

- (void)setHeaderValueWithAttributedString:(NSAttributedString *)attributedString titles:(NSArray *)titles {
    NSMutableAttributedString *textGold = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
    for (NSInteger i = titles.count - 1; i >= 0; i--) {
        UIControl *control = [self createControlWithTitle:titles[i] size:(CGSizeMake(50, 10))];
        @weakify(self);
        [control cms_addEventHandler:^(id  _Nonnull sender) {
            @strongify(self);
            if (self.didSelectItemBlock) {
                self.didSelectItemBlock(i, titles[i]);
            }
            
        } forControlEvents:UIControlEventTouchUpInside];
        
        NSMutableAttributedString *attachTextRecahrage = [NSMutableAttributedString
                                                          attachmentStringWithContent:control
                                                                                                       contentMode:UIViewContentModeLeft
                                                                                                    attachmentSize:CGSizeMake(60, 10)
                                                                                                       alignToFont:[UIFont systemFontOfSize:10]
                                                                                                         alignment:YYTextVerticalAlignmentCenter];
//        [textGold  appendAttributedString:attachTextRecahrage];
        [textGold insertAttributedString:attachTextRecahrage atIndex:0];
    }
//    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(self.headerLabel.width, self.headerLabel.height)]; //图文混排需要的宽度及高度
//    YYTextLayout *textLayout = [YYTextLayout layoutWithContainer:container text:textGold];
//    self.headerLabel.textLayout = textLayout;
    self.headerLabel.attributedText = textGold;
}

- (void)setModel:(CMSChartsContentModel *)model {
    _model = model;

    [CMSChartsTool setLeftRightAxisWithChartView:self.chartsView model:model];
    
//    [self setHeaderValueWithAttributedString:model.attributedString titles:model.tagTitles];
    if (model.chartData) {
        self.chartsView.data = model.chartData;
        BarLineScatterCandleBubbleChartDataSet *set = self.chartsView.data.dataSets.firstObject;
        set.highlightColor = [UIColor blackColor];
        set.highlightLineDashLengths = nil;

        [self reSetStyle:self.chartsView];

        /// 开局移动到最右边xMax为最大x轴值
        [self.chartsView moveViewToX:self.chartsView.data.xMax];
    } else {
        self.chartsView.data = nil;
    }
     
    [self setNeedsDisplay];
}

- (void)reSetStyle:(BarLineChartViewBase *)chart {
    [chart setVisibleXRangeWithMinXRange:10 maxXRange:410];
}

#pragma mark - K线视图

- (void)setupUIChartsView {
    [self addSubview:self.chartsView];
}

- (CombinedChartView *)chartsView {
    if (!_chartsView) {
        _chartsView = [[CombinedChartView alloc] init];
        _chartsView.highlighter.style = IHighlighterStyleCrossLine;
        //缩放样式
//        [MarketSetting setZoomStyleForChart:_chartsView];
        //空视图样式
        [MarketSetting setEmptyStyleForChart:_chartsView];
        //右边刻度样式
//        [MarketSetting setRightCalibrationStyleForChart:_chartsView andShowCount:7];
        
        //底部横轴样式
//        [MarketSetting setBottomCalibrationStyleForChart:_chartsView andIsShow:YES withShowCount:3];

        // 左边刻度样式
        [MarketSetting setLeftCalibrationStyleForChart:_chartsView andShowCount:5];
        CMSChartsMarker *marker = [[CMSChartsMarker alloc]
                                 initWithColor: UIColor.darkGrayColor
                                 font: [UIFont systemFontOfSize:12.0]
                                 textColor: UIColor.whiteColor
                                 insets: UIEdgeInsetsMake(5, 5, 5, 5)];
        marker.chartView = _chartsView;
//        marker.directions = @[];
        _chartsView.marker = marker;

        //整体样式
//        [MarketSetting setGradStyleForChart:_chartsView
//                      andShowGridBackground:false
//                                withBGColor:UIColor.clearColor
//                             andShowBorders:false
//                             andBorderColor:UIColor.clearColor
//                             withEdgeInsets:(UIEdgeInsetsMake(10, 10, 0, 0)) andDelegate:self];
        _chartsView.delegate = self;
    }
    return _chartsView;
}

#pragma mark - headerView

- (void)setupUIHeaderView {
    [self addSubview:self.headerLabel];
}

- (YYLabel *)headerLabel {
    if (!_headerLabel) {
        _headerLabel = [[YYLabel alloc] init];
        _headerLabel.backgroundColor = UIColor.blueColor;
        _headerLabel.textAlignment = NSTextAlignmentLeft;
        _headerLabel.numberOfLines = 2;
        _headerLabel.lineBreakMode = NSLineBreakByCharWrapping;
        _headerLabel.font = [UIFont systemFontOfSize:25];
    }
    return _headerLabel;
}

#pragma mark - ChartViewDelegate

/// 图表被移动(主、副图同时响应)
/// https://blog.csdn.net/dianchidu6913/article/details/101228178
/// - Parameters:
///   - chartView: ChartViewBase
///   - dX: CGFloat
///   - dY: CGFloat
- (void)chartTranslated:(ChartViewBase *)chartView dX:(CGFloat)dX dY:(CGFloat)dY {
    [self updateTouchForChartView:chartView];
}

/// 图表被缩放
/// - Parameters:
///   - chartView: ChartViewBase
///   - scaleX: CGFloat
///   - scaleY: CGFloat
- (void)chartScaled:(ChartViewBase *)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY {
    [self updateTouchForChartView:chartView];
}

/// 同步手势
/// - Parameter chartView: chartView description
- (void)updateTouchForChartView:(ChartViewBase *)chartView {
    CGAffineTransform srcMatrix = chartView.viewPortHandler.touchMatrix;
    if (self.updateTouchBlock) {
        self.updateTouchBlock(srcMatrix);
    }
}

- (void)chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight {
    if (self.chartValueSelectedBlock) {
        self.chartValueSelectedBlock(chartView, entry, highlight);
    }
}

- (void)chartValueNothingSelected:(ChartViewBase *)chartView {
    if (self.chartValueNothingSelectedBlock) {
        self.chartValueNothingSelectedBlock(chartView);
    }
}

- (BOOL)chartViewHighlight:(ChartViewBase *)chartView recognizer:(UIGestureRecognizer *)recognizer {
    if (self.chartViewCanHighlight) {
        return self.chartViewCanHighlight(chartView, recognizer);
    }
    return YES;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    self.headerLabel.preferredMaxLayoutWidth = self.width;
    [self setHeaderValueWithAttributedString:self.model.attributedString titles:self.model.tagTitles];
    
    CGSize maxSize = CGSizeMake(self.width, 30);
    //计算文本尺寸
    YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:maxSize text:self.headerLabel.attributedText];
    self.headerLabel.textLayout = layout;
    
    self.headerLabel.frame = CGRectMake(0, 0, self.width, MIN(layout.textBoundingSize.height, 30));
    
    self.chartsView.frame = CGRectMake(0, CGRectGetMaxY(self.headerLabel.frame), self.width, self.height - CGRectGetMaxY(self.headerLabel.frame));
}

@end
